package com.dy.yunying.biz.utils;

import com.pig4cloud.pig.common.core.exception.BusinessException;
import com.sjda.framework.common.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;

public class UploadUtils {

	private static Logger logger = LoggerFactory.getLogger(UploadUtils.class);
	//图片的后缀
	public static final String[] IMAGE_EXT = new String[] { "jpg", "jpeg", "gif", "png", "bmp" };
	/**
	 * 图片上传
	 * @param realPath
	 * @param imgFile
	 * @return
	 */
	public static Map<String, Object> imageUpload(String realPath, MultipartFile imgFile, long size){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(imgFile != null){
			if (size != 0 && size < imgFile.getSize()) {
				resultMap.put("error", 1);
				resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
				resultMap.put("message", "上传文件不可超过" + (size/1024) + "KB");
				logger.error("上传文件过大...上传文件不可超过" + (size/1024) + "KB");
				return resultMap;
			}
			InputStream in = null;
			FileOutputStream out = null;
			try {
				File absoluteDirFile = new File(realPath);
				if(!absoluteDirFile.exists()){
					absoluteDirFile.mkdirs();
					// linux 设置文件读取权限 部署时要将本行注释释放
					if (SysUtil.isLinux()){
						Runtime.getRuntime().exec("chmod 755 -R " +  absoluteDirFile.getPath());
					}
				}
				//获取图片名称
				String filename = imgFile.getOriginalFilename();
				//获取后缀名
				String suffix = filename.substring(filename.lastIndexOf(".") + 1);
				//判断是否是图片
				if(!getIsImg(suffix)){
					resultMap.put("error", 1);
					resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
					resultMap.put("message", "上传文件格式不正确");
					logger.error("上传文件格式不正确");
					return resultMap;
				}
				// 生成上传到服务器上的文件名 使用MD5对当前上传时间进行加密的方式
				UUID uuid = UUID.randomUUID();
				String realName = uuid + "." + suffix;
				in = imgFile.getInputStream();
				out = new FileOutputStream(realPath + File.separator + realName);
				int length = 0;
				byte[] b = new byte[1024];
				while ((length = in.read(b)) != -1){
					out.write(b, 0, length);
				}
				// linux 设置文件读取权限 部署时要将本行注释释放
				if (SysUtil.isLinux()){
					Runtime.getRuntime().exec("chmod 755 -R " +  realPath + File.separator + realName);
				}
				resultMap.put("filename", realName);
				logger.info("文件上传成功");
				resultMap.put("error", 0);
				resultMap.put("status", ResultData.StatusEnum.SUCCESS.getStatus());
				resultMap.put("message", "文件上传成功");
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put("error", 1);
				resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
				resultMap.put("message", "文件上传失败");
			} finally {
				try {
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else {
			resultMap.put("error", 1);
			resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
			resultMap.put("message", "请选择文件");
		}
		return resultMap;
	}

	/**
	 * 文件上传
	 *
	 * @param realPath
	 * @param imgFile
	 */
	public static void fileUpload(MultipartFile imgFile, String realPath, String fileName) {
		InputStream in = null;
		FileOutputStream out = null;
		try {
			File absoluteDirFile = new File(realPath);
			if (!absoluteDirFile.exists()) {
				absoluteDirFile.mkdirs();
				// linux 设置文件读取权限 部署时要将本行注释释放
				if (SysUtil.isLinux()) {
					Runtime.getRuntime().exec("chmod 755 -R " + absoluteDirFile.getPath());
				}
			}
			in = imgFile.getInputStream();
			out = new FileOutputStream(realPath + File.separator + fileName);
			int length = 0;
			byte[] b = new byte[1024];
			while ((length = in.read(b)) != -1) {
				out.write(b, 0, length);
			}
//                // linux 设置文件读取权限 部署时要将本行注释释放
//                if (SysUtil.isLinux()){
//                    Runtime.getRuntime().exec("chmod 755 -R " +  realPath + File.separator + fileName);
//                }
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			throw new BusinessException(11, "文件上传失败");
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				logger.error("文件流操作异常", e);
			}
		}
	}


	/**
	 * 图片上传
	 * @param realPath
	 * @param imgFile
	 * @return
	 */
	public static Map<String, Object> imageUpload(String realPath, MultipartFile imgFile, long size, String prefix, Locale locale){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if(imgFile != null){
			if (size != 0 && size < imgFile.getSize()) {
				resultMap.put("error", 1);
				resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
				if(locale.getLanguage().equals("zh"))
					resultMap.put("message", "上传文件不可超过" + (size/1024) + "KB");
				else
					resultMap.put("message", "Uploading files can not exceed " + (size/1024) + "KB");
				logger.error("上传文件过大...上传文件不可超过" + (size/1024) + "KB");
				return resultMap;
			}
			InputStream in = null;
			FileOutputStream out = null;
			try {
				//获取图片名称
				String filename = imgFile.getOriginalFilename();
				//获取后缀名
				String suffix = filename.substring(filename.lastIndexOf(".") + 1);
				//判断是否是图片
				if(!getIsImg(suffix)){
					resultMap.put("error", 1);
					resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
				     if(locale.getLanguage().equals("zh"))
				         resultMap.put("message", "上传文件格式不正确");
				     else
				         resultMap.put("message", "Uploading file format is incorrect");
					logger.error("上传文件格式不正确");
					return resultMap;
				}
				// 判断文件存放路径是否存在，若不存在则新建
				File dir = new File(realPath);
				if (!dir.exists()) {
					dir.mkdir();
				}
				// 生成上传到服务器上的文件名 使用MD5对当前上传时间进行加密的方式
				String realName =prefix + "." + suffix;
				in = imgFile.getInputStream();
				out = new FileOutputStream(dir.getPath() + File.separator + realName);
				int length = 0;
				byte[] b = new byte[1024];
				while ((length = in.read(b)) != -1){
					out.write(b, 0, length);
				}
				// linux 设置文件读取权限 部署时要将本行注释释放
				if (SysUtil.isLinux()) {
					Runtime.getRuntime().exec("chmod 755 " + dir.getPath()  + File.separator + realName);
				}
				resultMap.put("filename", realName);
				logger.info("文件上传成功");
				resultMap.put("error", 0);
				resultMap.put("status", ResultData.StatusEnum.SUCCESS.getStatus());
				resultMap.put("message", "文件上传成功");
			} catch (Exception e) {
				e.printStackTrace();
				resultMap.put("error", 1);
				resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
				if(locale.getLanguage().equals("zh"))
				  resultMap.put("message", "文件上传失败");
				else
				  resultMap.put("message", "Upload failure");
			} finally {
				try {
					if(in != null){
						in.close();
					}
					if(out != null){
						out.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else {
			resultMap.put("error", 1);
			resultMap.put("status", ResultData.StatusEnum.ERROR.getStatus());
			resultMap.put("message", "请选择文件");
		}
		return resultMap;
	}


	/**
	 * 是否是图片
	 * @param ext
	 * @return "jpg", "jpeg", "gif", "png", "bmp" 为文件后缀名者为图片
	 */
	public static boolean getIsImg(String ext) {
		ext = ext.toLowerCase();
		for (String s : IMAGE_EXT) {
			if (s.equalsIgnoreCase(ext)) {
				return true;
			}
		}
		return false;
	}
}
